package basic.arch.component.lock.distributed;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import basic.arch.component.lock.aop.annotation.Lock;

/**
 * @author jannal
 */
@Service("distributionLockSpringApplicationContextHolder")
public class DistributionLockSpringApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        DistributionLockSpringApplicationContextHolder.applicationContext = applicationContext;
        Map<String, DistributionLock> map = applicationContext.getBeansOfType(DistributionLock.class);
        distributionLockBeanImplMap = new HashMap<Lock.DisstributionLockType, DistributionLock>();
        Set<Entry<String, DistributionLock>> entrySet = map.entrySet();
        Iterator<Entry<String, DistributionLock>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Entry<String, DistributionLock> entry = iterator.next();
            distributionLockBeanImplMap.put(entry.getValue().getType(), entry.getValue());
        }

    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContext.getBean(beanName, clazz);
    }

    private static Map<Lock.DisstributionLockType, DistributionLock> distributionLockBeanImplMap;

    public static <T extends DistributionLock> T getDistributionLock(Lock.DisstributionLockType disstributionLockType) {
        return (T) distributionLockBeanImplMap.get(disstributionLockType);
    }
}